import { syncSetTimeout, sendMessage, getMessage, dispatch } from "../../global/tools.js";

export default class TextLinkage {
    static count = 0;
    constructor(webController) {
        TextLinkage.count++;
        if (TextLinkage.count >= 2) {
            alert("collectionPlugin: \nError: TextLinkage.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        this.webController = webController;
        this.config = {
            allowClickSave: true
        };
        // 监听事件
        {
            this.eventListenersFn = {
                click: {
                    title: "click",
                    capture: true,
                    fn: async e => {
                        if (e.target.innerText == "提交催记") {
                            let target = jQuery("#refundForm label:contains('催收备注:')").next().find("textarea");
                            if ((jQuery("div.key:contains('逾期天数')").next().eq(0).text() >= 76) && (jQuery("div.info > .names").text() === "焦文轩") && (target.length === 1)) {
                                target.val("CalledTwice，" + target.val());
                                dispatch(target, "input");
                                dispatch(target, "change");
                                await syncSetTimeout(100);
                            } else if ((jQuery("div.key:contains('逾期天数')").next().eq(0).text() >= 60) && (jQuery("div.info > .names").text() === "焦文轩") && (target.length === 1)) {
                                target.val("Called，" + target.val());
                                dispatch(target, "input");
                                dispatch(target, "change");
                                await syncSetTimeout(100);
                            }
                        }
                    }
                },
                keydown: {
                    title: "keydown",
                    fn: async e => {
                        const keyToStr = {
                            "1": "承诺还款",
                            "2": "已还款",
                            "3": "语音留言",
                            "z": "拒接",
                            "x": "无人接听",
                            "c": "无法接通",
                            "v": "停机",
                            "b": "空号",
                            "n": "关机"
                        };
                        if (Object.keys(keyToStr).includes(e.key) && e.altKey) {
                            this.keyLinkage(keyToStr[e.key]);
                        }
                        if (e.key == "`" && e.altKey && this.config.allowClickSave) {
                            // 简单防抖
                            {
                                this.config.allowClickSave = false;
                                setTimeout(() => {
                                    this.config.allowClickSave = true;
                                }, 2000);
                            }
                            let target = jQuery("div.refund-box > div.refund-title > span:contains('填写催记')").parent().parent().find("button:contains('提交催记')");
                            if (target.length === 1) {
                                dispatch(target, "click");
                            }
                        }
                    }
                }
            };
            // 开始监听相关事件
            for (const key in this.eventListenersFn) {
                this.webController.document().addEventListener(this.eventListenersFn[key].title, this.eventListenersFn[key].fn, this.eventListenersFn[key].capture ? true : false);
            }
        }
        this.init();
    }
    init() {

    }
    async keyLinkage(str) {
        switch (str) {
            case "承诺还款":
                await this.option1("承诺还款");
                await this.option2("三日内承诺处理");
                await this.option3("忘记处理");
                await this.option4("客户承诺今天还款，店铺在营");     
                break;
            case "已还款":
                await this.option1("已还款");
                await this.option2("声称已还款");
                await this.option3("已还款");
                await this.option4("客户承诺今天已经还款，店铺在营");  
                break;
            case "语音留言":
                await this.option1("非本人接电");
                await this.option2("语音留言转告");
                await this.option3("正常接通");
                await this.option4("语音留言");
                break;
            case "拒接":
                await this.option1("未联系上");
                await this.option2("未联系上");
                await this.option3("拒接");
                await this.option4("拒接");
                break;
            case "无人接听":
                await this.option1("未联系上");
                await this.option2("未联系上");
                await this.option3("无人接听");
                await this.option4("无人接听");
                break;
            case "无法接通":
                await this.option1("未联系上");
                await this.option2("未联系上");
                await this.option3("无法接通");
                await this.option4("无法接通");
                break;
            case "停机":
                await this.option1("未联系上");
                await this.option2("未联系上");
                await this.option3("停机");
                await this.option4("停机");
                break;
            case "空号":
                await this.option1("未联系上");
                await this.option2("未联系上");
                await this.option3("空号");
                await this.option4("空号");
                break;
            case "关机":
                await this.option1("未联系上");
                await this.option2("未联系上");
                await this.option3("关机");
                await this.option4("关机");
                break;
            default:
                break;
        }
        if (this.webController?.auto?.config?.autoCall && (!str.includes("还款"))) {
            await syncSetTimeout(100);
            this.eventListenersFn.keydown.fn({
                key: "`",
                altKey: true
            });
        }
    }
    // 催收进程
    async option1(text) {
        let target1 = jQuery("label:contains('催收进程:')").next("div.ivu-form-item-content").find("div.ivu-select-selection");
        if (target1.length === 1) {
            target1.click();
            await syncSetTimeout(500);
        } else {
            console.error("[collectionPlugin]", "Error: anmi -> modules -> TextLinkage -> option1() -> target1.length != 1", `target1.length === ${target1.length}`);
        }
        
        let target2 = jQuery(`div[x-placement='top-start'] > ul.ivu-select-dropdown-list > li.ivu-select-item:contains('${text}')`);
        if (target2.length === 0) {
            target2 = jQuery(`div[x-placement='bottom-start'] > ul.ivu-select-dropdown-list > li.ivu-select-item:contains('${text}')`)
        }
        target2.click();
        // if (target2.length === 1) {
        //     target2.click();
        //     await syncSetTimeout(100);
        // } else {
        //     console.error("[collectionPlugin]", "Error: anmi -> modules -> TextLinkage -> option1() -> target2.length != 1", `target2.length === ${target2.length}`, target2);
        // }
    }
    // 催收结果
    async option2(text) {
        let target = jQuery("label:contains('催收结果:')").next("div.ivu-form-item-content").find(`span:contains('${text}')`).prev("span.ivu-radio").find("input.ivu-radio-input[type='radio']");
        if (target.length === 1) {
            target.click();
            await syncSetTimeout(100);
        } 
    }
    // 电话结果
    async option3(text) {
        let target = jQuery("label:contains('电话结果:')").next("div.ivu-form-item-content").find(`span:contains('${text}')`).prev("span.ivu-radio").find("input.ivu-radio-input[type='radio']");
        if (target.length === 1) {
            target.click();
            await syncSetTimeout(100);
        }
    }
    // 催收备注
    async option4(text) {
        if (!jQuery("div.key:contains('产品名称')").next().eq(0).text().includes("天行用呗逾期")) {
            text = text.replace("，店铺在营", "");;
        }
        let target = jQuery("#refundForm label:contains('催收备注:')").next().find("textarea");
        if (target.length === 1) {
            target.val(text);
            dispatch(target, "input");
            dispatch(target, "change");
            await syncSetTimeout(100);
        }
    }
}